package com.goodluck.goodluckim.sdk.service;

import com.goodluck.goodluckim.db.DBManager;
import com.goodluck.goodluckim.db.greendao.RecentSessionDao;
import com.goodluck.goodluckim.db.model.IMMessage;
import com.goodluck.goodluckim.db.model.RecentSession;
import com.goodluck.goodluckim.sdk.event.SessionEvent;
import com.hwangjr.rxbus.RxBus;

/**
 * 会话消息管理器
 * Created by GLC-009 on 2018/9/14.
 */

public class SessionService {
    private RecentSessionDao recentSessionDao;

    public SessionService() {
        recentSessionDao = DBManager.getInstance().getDaoSession().getRecentSessionDao();
    }

    /**
     * 设置会话数据
     *
     * @param message
     */
    public void setSession(IMMessage message) {
        RecentSession recentSession = recentSessionDao.queryBuilder().where(RecentSessionDao.Properties.SessionID.eq(message.getSessionID())).unique();
        if (recentSession == null) {
            recentSession = new RecentSession(message.getId(), message.getMessageId(),
                    message.getMessageDirection(), message.getSenderUserId(), message.getReceivedTime(), message.getReceivedStatus(),
                    message.getSendTime(), message.getSendStatus(), message.getObjectName(), message.getMessageContent(),
                    message.getAttachStatus(), 0, message.getReceiveId(), message.getSessionType(),
                    message.getMessageType(), message.getSessionID(), message.getMsgAttachment(), message.getAttachStatus(), message.getExtra());
            recentSessionDao.insertOrReplace(recentSession);
            RxBus.get().post(new SessionEvent(SessionEvent.EventType.ADD_SESSSION, recentSession));
        } else {
            recentSession.setReadReceiptInfo(recentSession.getReadReceiptInfo() + 1);
            recentSession.setMessageContent(message.getMessageContent());
            recentSession.setReceivedTime(message.getReceivedTime());
            recentSession.setSenderUserId(message.getSenderUserId());
            recentSession.setReceiveId(message.getReceiveId());
            recentSession.setExtra(message.getExtra());
            recentSessionDao.update(recentSession);
            RxBus.get().post(new SessionEvent(SessionEvent.EventType.UPDATE_SESSION, recentSession));
        }
    }
}
